package com.chinaway.mobile.http.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import com.chinaway.proxy.Proxy;
 


/**
 *  类封装了虚拟浏览器的一些基本操作
 */
public class ClientOperate {
	protected final static Log log = LogFactory.getLog(ClientOperate.class);
	/**
	 * 处理一个实体
	 * 找到指定的字符串
	 */
	
	public StringBuffer processEntity(HttpEntity entity,String encodType) {
		StringBuffer sb = new StringBuffer();
		InputStreamReader iReader = null;
		try {
			// 从消息实体中获取输入流对象
			InputStream inputStream = entity.getContent();
			iReader = new InputStreamReader(inputStream,encodType);
			BufferedReader reader = new BufferedReader(iReader);
			String line = null;
			// 用reader.ready()是不行的，这是用来判断此流是否已准备好被读取
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\r\n");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				iReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb;
	}
	/**
	 * 判断服务器页面是否重定向
	 * 
	 * @param statuscode
	 *            response中的状态码
	 * @return
	 */
	public  boolean ifRedirect(int statusCode) {
		boolean flag = false;
		if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
				|| (statusCode == HttpStatus.SC_SEE_OTHER)
				|| (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
			flag = true;
		}
 
		return flag;
	}
	/**
	 * 打印服务器返回的状态
	 * @param response
	 */
	public int getResponseStatus(HttpResponse response){
		StatusLine sl = response.getStatusLine() ;
		log.info(response.getStatusLine()); // 服务器返回状态
		return sl.getStatusCode();
	}
	/**
	 * 打印返回的头部信息
	 * @param response
	 */
	public void printAllHeaders(HttpResponse response){
		Header[] headers = response.getAllHeaders(); // 返回的HTTP头信息
		for (int i = 0; i < headers.length; i++) {
			log.info(headers[i]);
		}
	}
	/**
	 * 打印cookie信息
	 * @param httpclient
	 */
	public void printCookie(DefaultHttpClient httpclient){
	        List<Cookie> cookies = httpclient.getCookieStore().getCookies();  
	        if (cookies.isEmpty()) {  
	        	log.info("None");  
	        } else {  
	            for (int i = 0; i < cookies.size(); i++) {  
	                log.info("Cookie-" + cookies.get(i).toString());  
	            }  
	        } 
	}
	/**
	 * 获得重定向
	 */
	 public String getRedirectLocation(HttpResponse response) {
	        Header locationHeader = response.getFirstHeader("Location");
	        if (locationHeader == null) {
	            return null;
	        }
	        return locationHeader.getValue();
	 }
	 
	 /**
	  * 获得String类容
	  */
	 public String getText(String flag,HttpClient httpclient,HttpContext localContext,String url) {
		 return getText(flag,httpclient,localContext,url,"UTF-8");
	 }
	 public String getText(String flag, HttpClient httpclient,HttpContext localContext,String url,String defaultCharset) {
		 
		 
		 HttpGet httpget = new HttpGet(url);
		 Header accept=new BasicHeader("Accept", "*/*");
		 Header lan=new BasicHeader("Accept-Language", "*/*");
		 Header headerhost=new BasicHeader("Host", "www.sd.10086.cn");
		 Header headerconn=new BasicHeader("Connection","keep-alive");
		 Header headerref=new BasicHeader("Referer", "http://www.sd.10086.cn/eMobile/jsp/common/prior.jsp");
		 httpget.addHeader(headerhost);
		 httpget.addHeader(headerconn);
		 httpget.addHeader(headerref);
		 httpget.addHeader(accept);
		 httpget.addHeader(lan);
		 
		 String text  = "" ;
		 HttpResponse  response = null ; 
		 try {
			 response = httpclient.execute(httpget, localContext);
			 
			 HttpEntity entity = response.getEntity();
			 
//			 prtCookies((CookieStore)localContext.getAttribute(ClientContext.COOKIE_STORE), flag);
			 
			 if(entity!=null){
				 text  =  EntityUtils.toString(entity, defaultCharset);   
			 }   
		 } catch (Exception e) {
			 text = "" ;
		 } finally {
			 httpget.abort();
		 }
		 return text;
	 }
	 
	 
	 public String getPostText(String flag,HttpClient httpclient,HttpContext localContext,String url,String defaultCharset) {
		 HttpPost httppost = new HttpPost(url);

		 Header accept=new BasicHeader("Accept", "*/*");
		 Header lan=new BasicHeader("Accept-Language", "*/*");
		 Header headerhost=new BasicHeader("Host", "www.sd.10086.cn");
		 Header headerconn=new BasicHeader("Connection","keep-alive");
		 Header headerref=new BasicHeader("Referer", "http://www.sd.10086.cn/eMobile/jsp/common/prior.jsp");
		 httppost.addHeader(headerhost);
		 httppost.addHeader(headerconn);
		 httppost.addHeader(headerref);
		 httppost.addHeader(accept);
		 httppost.addHeader(lan);
		 String text  = "" ;
		 HttpResponse  response = null ; 
		 try {
			 response = httpclient.execute(httppost, localContext);
			 HttpEntity entity = response.getEntity();
//			 prtCookies((CookieStore)localContext.getAttribute(ClientContext.COOKIE_STORE), flag);
			 if(entity!=null){
				 text  =  EntityUtils.toString(entity, defaultCharset);   
			 }   
		 } catch (Exception e) {
			 text = "" ;
		 } finally {
			 httppost.abort();
		 }
		 return text;
	 }
	 
	 public static void prtCookies(CookieStore cookieStore,String flag){
		 // 查看 cookie 信息  
	      List<Cookie> cookies = cookieStore.getCookies();
	      if (cookies.size() == 0) {  
	         System.out.println( flag+":::"+"cookies None" );  
	      } else {  
	         for ( int i = 0; i < cookies.size(); i++) {  
	            System.out.println(flag+":::"+cookies.get(i).getName()+"==="+cookies.get(i).getValue());  
	         }  
	      }  
	}
	
	 
		
	/**
	 * 获得reponse
	 */
	public HttpResponse getResponse(DefaultHttpClient httpclient, HttpContext localContext, String url) {
		HttpGet httpget = new HttpGet(url);
		HttpResponse response = null;
		try {
			response = httpclient.execute(httpget, localContext);
		} catch (ClientProtocolException e) {
			response = null;
		} catch (IOException e) {
			response = null;
		} finally {
			 httpget.abort();
				
		 }
		return response;

	}
	 /**
	  * 获得reponse
	  */
	 public String getResponse(HttpClient httpclient,HttpContext localContext,String url,RespProcess respProcess) throws ClientProtocolException,IOException {
			HttpResponse  response = null ;
			String res = "" ;
			HttpGet httpget = new HttpGet(url);
			try {
				response = httpclient.execute(httpget,localContext);
				res = respProcess.doProcess(response);
			}finally {
				httpget.abort();
	        }
			return res ;
			 
		}
	public static interface RespProcess {
		String doProcess(HttpResponse  response);
	}
	
	
	 public static String getTextByProxy(String url,String defaultCharset,Proxy proxy) {
		// 创建 HttpParams 以用来设置 HTTP 参数（这一部分不是必需的）  
        HttpParams httpParams = new BasicHttpParams();  
        //设置代理ip
		HttpHost hostProxy = new HttpHost(proxy.getIp(),proxy.getPort());
		httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, hostProxy);
		
		//设置连接时间和超时时间均为2秒
		HttpConnectionParams.setConnectionTimeout(httpParams, 6000);  
		HttpConnectionParams.setSoTimeout(httpParams, 6000);  
		DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);
		 
		 HttpGet httpget = new HttpGet(url);
		 String text  = "" ;
		 HttpResponse  response = null ; 
		 try {
			 response = httpclient.execute(httpget);
			 HttpEntity entity = response.getEntity();
			 if(entity!=null){
				 text  =  EntityUtils.toString(entity, defaultCharset);   
			 }   
		 } catch (Exception e) {
			 text = "" ;
		 } finally {
			 httpget.abort();
		 }
		 return text;
	 }
	
	 public static volatile FileReader reader = null;
	 public static String getWTFPC(){
		 String jsFileName = "data/mobile/js/WT.js";   // 读取js文件 
		
		 try {
			 	ScriptEngineManager manager = new ScriptEngineManager();   
				ScriptEngine engine = manager.getEngineByName("javascript");     
				if(null == reader){
					 File f = new File(jsFileName);
					log.info("WT.js路径"+ f.getAbsolutePath());
					reader = new FileReader(jsFileName);   // 执行指定脚本   
				}
				
				engine.eval(reader);   
				if(engine instanceof Invocable) {    
				Invocable invoke = (Invocable)engine;    // 调用merge方法，并传入两个参数    
				return (String)invoke.invokeFunction("WT");   
			}
		} catch (Exception e) {
//			log.info("WT.js路径"+ f.getAbsolutePath(),e);
			e.printStackTrace();
		}
		return null;
	 }
	 
//	 public static void addWTFPC2Cookies(CookieStore cookieStore){
//		 String wt=getWTFPC();
//	     Cookie c=new BasicClientCookie("WT-FPC", wt);
//	     cookieStore.addCookie(c);
//	}
	
//	 public static void main(String[] args) {
//	System.out.println(getWTFPC());	
//	}
}
